layui.use(['jquery', 'layer', 'table', 'form', 'configs'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        table = layui.table,
        form = layui.form,
        config = layui.configs;

    //全局变量：表格列
    var cols = [
        {field: 'confKey', title: '参数名'}
        , {field: 'confValue', title: '参数值'}
        , {field: 'confDesc', title: '参数描述'}
        , {fixed: 'right', title: '操作', width: 150, align: 'center', toolbar: '#rowOperate'}
    ];

    //查全部
    getTableData();
    initTable();

    function initTable() {
        table.render({
            elem: '.settingTable'
            , id: 'sys-table'
            , data: []
            , autoSort: false
            , toolbar: '#toolbarSystem'
            , defaultToolbar: ['filter']
            , cols: [cols]
            , page: {
                layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                , groups: 1 //只显示 5 个连续页码
                , first: false
                , last: false
                , limits: [15, 30, 45, 60, 75, 90]
            }
        });
    }

    function getTableData(datas) {
        $.ajax({
            //url: "./json/sys.json",
            url: config.motorBaseUrl + "/config/configAll/v2.0",
            type: "post",
            datatype: "json",
            data: datas,
            success: function (result) {
                table.render({
                    elem: '.settingTable'
                    , id: 'sys-table'
                    , data: result.data
                    , autoSort: false
                    , toolbar: '#toolbarSystem'
                    , defaultToolbar: ['filter']
                    , cols: [cols]
                    , page: {
                        layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                        , groups: 1 //只显示 5 个连续页码
                        , first: false
                        , last: false
                        , limits: [10, 20, 50, 100, 500]
                    }
                    , limit: 10
                    , loading: true
                    , done: function (res) {
                        //tdTitle();
                    }
                });
                //allDeviceData = result.data;
            }
        })
    }

    //头工具栏事件--新增
    table.on('toolbar(setSystemTable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        var event = obj.event;
        if (event === 'searchParms') { //查询
            layer.open({
                type: 1,
                title: "查询",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#searchParm').html(),
                yes: function (index, layero) { //确定
                    var datas = layero.find($("form")).serialize();
                    layer.close(index);
                    getTableData(datas);
                },
                btn2: function (index, layero) { //取消
                    layer.close(index);
                }
            });
        } else if (event === 'addParms') { //新增
            var layerIdx = layer.open({
                type: 1,
                title: "新增",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#newAdd').html(),
                success: function (layero, index) {
                    form.render();
                }
            });
            form.on('submit(AddForm)', function (res) {
                console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
                addDevice(res.field);
                layer.close(layerIdx);
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
            //取消
            $(".addParm button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });


    //监听工具条
    table.on('tool(setSystemTable)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        if (layEvent === 'del') { //删除
            layer.confirm('真的删除吗？', function (index) {
                var dataobj = {
                    "id": data.id,
                    "confKey": data.confKey
                };
                deleteDevice(obj,dataobj);
                layer.close(index);
            });
        } else if (layEvent === 'edit') { //编辑
            var layerIdx = layer.open({
                type: 1,
                title: "编辑",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#rowEdit').html(),
                success: function (layero, index) {
                    form.render();
                    form.val("rowEditForm", data);
                    form.render();
                }
            });
            form.on('submit(rowEditForm)', function (res) {
                //console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
                updateDevice(obj,res.field);
                layer.close(layerIdx);
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
            //取消
            $(".editParm button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });

    //新增
    function addDevice(dataObj) {
        $.ajax({
            url: config.motorBaseUrl + "/config/insert/v2.0",
            type: "post",
            datatype: "json",
            data: dataObj,
            success: function (result) {
                if (result.stateCode == 0) {
                    tableReload();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //更新
    function updateDevice(obj,datas) {
        $.ajax({
            url: config.motorBaseUrl + "/config/upConfig/v2.0",
            type: "post",
            datatype: "json",
            data: datas,
            success: function (result) {
                if (result.stateCode == 0) {
                    refreshTable("update",obj,datas);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //删除
    function deleteDevice(obj,dataobj) {
        $.ajax({
            url: config.motorBaseUrl + "/config/deleteById/v2.0",
            type: "post",
            datatype: "json",
            data: dataobj,
            success: function (result) {
                if (result.stateCode == 0) {
                    refreshTable('delete',obj);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    function tableReload() {
        table.reload("sys-table", {
            url: config.motorBaseUrl + "/config/configAll/v2.0",
            where: {
                confKey: '',
                confValue: ''
            }
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.stateCode, //解析接口状态
                    "msg": res.stateMsg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        })
    }

    function refreshTable(type,obj,data){
        if(type == "update"){
            obj.update(data); //同步更新缓存对应的值
        }else if(type == "delete"){
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        }
    }
});
